/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

var Router = require('koa-router');
var config = require('../../config/index.js');
var appUtil = require('../../common/appUtils.js');
let bodyParser = require('koa-better-body');
let koabody = bodyParser();

let customerCmdService = require('../../ddd/application/customerCmdService.js');
let customerQueryService = require('../../ddd/application/customerQueryService.js');

//
var __pathPrefix = '/api/v1/customer';
appUtil.appLog('router:' + __pathPrefix + ',file=' + __filename);
var router = new Router({prefix: __pathPrefix});
module.exports = router.routes();


/**
 * 检测登录状态
 */
function checkLogin(ctx) {
  let customer = ctx.session.customer;
  return customer;
}

/**
 * 商品检索,无身份验证
 * get /api/v1/customer/ware?categoryid=xx&locationid=xx
 */
router.get('/ware', koabody, function*() {
  let categoryId = this.request.query.categoryid;
  let locationId = this.request.query.locationid;
  this.body = yield customerQueryService.customerWare(locationId, categoryId);
});

/**
 * 添加到购物车,需身份验证
 */
router.post('/cart', koabody, function*() {
  let customer = checkLogin(this);
  if (!customer) {
    this.status = 401;
    return this.body = 'not customer';
  }

  let wareId = this.request.body.fields.wareId;
  let wareCount = this.request.body.fields.wareCount;
  let resultOrder = yield customerCmdService.addUnpaidOrder(customer.id, wareId, wareCount);
  this.body = resultOrder;
});

// get all order
router.get('/order', function*() {
  let customer = checkLogin(this);
  if (!customer) {
    this.status = 401;
    return this.body = 'not customer';
  }

  let orders = yield customerQueryService.customerOrder(customer.id);
  console.log(orders);
  this.body = orders;
});

/**
 * pay the order
 * 不需身份验证（自己的订单，可以由别人支付)
 */
router.post('/order/pay', koabody, function*() {
  let orderId = this.request.body.fields.orderId;
  let result = yield customerCmdService.payOrder(orderId);
  this.body = result;
});

/**
 * order detail
 */
router.get('/order/:id', function*() {
  let customer = checkLogin(this);
  if (!customer) {
    this.status = 401;
    return this.body = 'not customer';
  }
  let orderId = this.params.id;
  let order = yield customerQueryService.customerOrderDetail(customer.id, orderId);
  this.body = order;
});